﻿using Newtonsoft.Json.Linq;

namespace CommonUtils
{
    public class Settings
    {
        const string basePath = "settings";

        public static JObject settings;

        public static void Save()
        {
            FileUtil.Save("settings.json", settings.ToString());
        }

        static Settings()
        {
            settings = JsonUtil.GetJObjectFromFile("settings.json");
            if (settings == null)
            {
                settings = new JObject();
                settings.Add("@key", "@value");
                Save();
            }
        }

        public static string GetString(string key, string defaultValue = default)
        {
            if (!settings.ContainsKey(key))
            {
                settings.Add(key, defaultValue);
                Save();
            }
            return settings.GetString(key, defaultValue);
        }

        public static void Set(string key, object value)
        {
            settings.Set(key, value);
            Save();
        }

        public static JObject GetSetting(string path)
        => JsonUtil.DeserializeFromFile(basePath.Combine(path));

        public static T GetSetting<T>(string path)
        => JsonUtil.DeserializeFromFile<T>(basePath.Combine(path));

    }
}
